<template>
  <div class="app-container">

    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">

          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="optionData" @change="selectOrgan" collapse-tags filterable></el-cascader>
          </el-form-item>

          <el-form-item>
            <el-input v-model="query.params.organName" clearable placeholder="组织名称" />
          </el-form-item>

          <el-form-item>
            <el-select v-model="query.params.status" clearable placeholder="状态"  style="width:100%">
              <el-option
                v-for="item in query.statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select v-model="query.params.type" clearable placeholder="类型"   style="width:100%">
              <el-option
                v-for="item in query.typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>


          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">签订协议与新增组织</el-button>
          </el-form-item>


        </el-form>
      </el-col>

    </div>

    <div class="block">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        row-key="id"
      >
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="组织名称" width="220">
          <template slot-scope="scope">
            {{ scope.row.organName }}
          </template>
        </el-table-column>
        <!--  <el-table-column label="父组织编号" width="120" >
          <template slot-scope="scope">
            {{ scope.row.parentId }}
          </template>
        </el-table-column> -->

        <el-table-column label="状态" width="120" prop="status" :formatter="statusFormat" />
        <el-table-column label="类型" width="120" prop="type" :formatter="typeFormat" />

        <!--  <el-table-column label="组织层次路径" width="110">
          <template slot-scope="scope">
            {{ scope.row.organPath }}
          </template>
        </el-table-column> -->

        <el-table-column label="备注" width="210">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>

        <el-table-column  fixed="right" align="center" prop="created_at" label="操作" >
          <template slot-scope="scope">
            <el-link v-has="'ORGAN_EDIT'" icon="el-icon-edit" type="warning" style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </el-link><el-divider v-has="'ORGAN_REMOVE'"  direction="vertical"></el-divider>
            <el-link v-has="'ORGAN_REMOVE'" class="el-icon-delete" type="danger" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link><el-divider   v-has="'ORGAN_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'ORGAN_EDIT'" type="warning" style="cursor: pointer;" @click="handleAssignAuthority(scope.$index, scope.row)">
              分配权限
            </el-link><el-divider v-has="'ROLE_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'ROLE_EDIT'" type="success" style="cursor: pointer;" @click="handleFetchRoleList(scope.$index, scope.row)">
              添加管理员角色
            </el-link><el-divider v-has="'SUB_ORGAN_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'SUB_ORGAN_EDIT'" type="success" style="cursor: pointer;" @click="handleAddSub(scope.$index, scope.row)">
              新增下级组织
            </el-link><el-divider  v-has="'MGR_USER_DEIT'"  direction="vertical"></el-divider>
            <el-link v-has="'MGR_USER_DEIT'" type="success" style="cursor: pointer;" @click="handleAddMgrUser(scope.$index, scope.row)">
              添加管理员账号
            </el-link><el-divider v-has="'ORGAN_CONF_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'ORGAN_CONF_EDIT'" type="success" style="cursor: pointer;" @click="handleAddSub(scope.$index, scope.row)">
              添加组织配置
            </el-link><el-divider  v-has="'ORAN_INFO_EDIT'"  direction="vertical"></el-divider>
            <el-link v-has="'ORAN_INFO_EDIT'" type="success" style="cursor: pointer;" @click="handleAddSub(scope.$index, scope.row)">
              添加组织详细信息
            </el-link><el-divider  v-has="'MERCHANT_EDIT'" direction="vertical"></el-divider>
            <el-link v-has="'MERCHANT_EDIT'" type="success" style="cursor: pointer;" @click="handleAddSub(scope.$index, scope.row)">
              添加组织商户信息
            </el-link><el-divider  v-has="'ORGANTYPEORGAN_ASSIGNEDORGANTYPEORGANS'"  direction="vertical"></el-divider>
            <el-link v-has="'ORGANTYPEORGAN_ASSIGNEDORGANTYPEORGANS'" type="success" style="cursor: pointer;" @click="handleAddOrganTypeAvaliableEdit(scope.$index, scope.row)">
              赋予可创建组织类型
            </el-link><el-divider  v-has="'DICTIONARYORGAN_ASSIGNEDDICTIONARY'" direction="vertical"></el-divider>
            <el-link v-has="'DICTIONARYORGAN_ASSIGNEDDICTIONARY'" type="success" style="cursor: pointer;" @click="handleAddDictionaryAvaliableEdit(scope.$index, scope.row)">
              引用字典
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="block">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form  :model="form" :rules="organRules" ref="organForm">

          <el-form-item v-if="addForVisible" label="编号" >
            <el-input v-model="form.id" disabled placeholder="编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="组织名称" required prop="organName">
            <el-input v-model="form.organName" placeholder="组织名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="组织层次路径" hidden>
            <el-input v-model="form.organPath" placeholder="组织层次路径" auto-complete="off" />
          </el-form-item>
          <el-form-item label="父组织编号" hidden>
            <el-input v-model="form.parentId" placeholder="父组织编号" auto-complete="off" />
          </el-form-item>

          <el-form-item label="状态" required>
            <el-select v-model="form.status" placeholder="状态"  style="width:100%">
              <el-option
                v-for="item in query.statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="类型" required>
            <el-select v-model="form.type" placeholder="类型"  style="width:100%">
              <el-option
                v-for="item in query.typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item label="组织类型" required>
            <el-select v-model="form.organType" @change.native="flushPage" placeholder="组织类型"  style="width:100%">
              <el-option
                v-for="item in query.organTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave('organForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormForAddMgrUserVisible">
        <el-form :model="user"   :rules="userRules" ref="userForm"  >

          <el-form-item v-if="addForVisible" label="用户编号">
            <el-input v-model="user.id" disable auto-complete="off" />
          </el-form-item>

          <el-form-item label="用户名" placeholder="用户名" required prop="userName">
            <el-input v-model="user.userName" clearable auto-complete="off" />
          </el-form-item>

          <el-form-item label="密码" placeholder="密码" required prop="password">
            <el-input type="password"
             v-model="user.password" 
             show-password="true" 
             clearable 
             auto-complete="off" />
          </el-form-item>

          <el-form-item label="是否超管" required prop="isSuperMgr">
            <el-select v-model="user.isSuperMgr" clearable placeholder="是否超管" style="width:100%">
              <el-option
                v-for="item in query.isSuperMgrOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="user.remark" clearable auto-complete="off" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormForAddMgrUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUserEditSave('userForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogForRoleAddVisible"
      >
        <el-form :model="form">

          <el-form-item v-if="addForVisible" label="角色编号">
            <el-input v-model="role.id" disabled placeholder="角色编号" auto-complete="off" />
          </el-form-item>

          <el-form-item label="角色名称">
            <el-input v-model="role.name" auto-complete="off" />
          </el-form-item>
          <el-form-item label="角色代码">
            <el-input v-model="role.code" auto-complete="off" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="role.type" placeholder="类型"  style="width:100%">
              <el-option
                v-for="item in query.roleTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogForRoleAddVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleMgrRoleSave">确 定</el-button>

        </div>
      </el-dialog>
    </div>


    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogForDictionaryAddVisible">
        <el-table
        ref="dictionaryListTable"
        v-loading="listLoading"
        :data="dictionaryList"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
        row-key="id"
      >
      <el-table-column
      type="selection"
      width="55">
    </el-table-column>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>

        <el-table-column label="描述" width="110">
          <template slot-scope="scope">
            {{ scope.row.desc }}
          </template>
        </el-table-column>
        <el-table-column label="代码" width="110">
          <template slot-scope="scope">
            {{ scope.row.code }}
          </template>
        </el-table-column>
        <el-table-column label="枚举值" >
          <template slot-scope="scope">
            {{ scope.row.value }}
          </template>
        </el-table-column>

      </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogForDictionaryAddVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDictionaryEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogForOrganTypeAvaliableEditVisible">
        <el-table
          ref= "organTypeSelectionTable"
          v-loading="listLoading"
          :data="organTypeList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          @selection-change="handleOrganTypeSelectionChange"
        >
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column label="组织类型名称" width="110">
            <template slot-scope="scope">
              {{ scope.row.organTypeName }}
            </template>
          </el-table-column>
          <el-table-column label="类型" prop="type" :formatter="organTypeFormater" >
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="organTypeListCurrentPage"
            :page-sizes="[5, 10, 20, 30, 40]"
            :page-size="organTypeListPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="organTypeListTotal"
            @size-change="organTypeListHandleSizeChange"
            @current-change="organTypeListHandleCurrentChange"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogForOrganTypeAvaliableEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleOrganTypeOrganSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="block">
            <!--弹框-->
      <el-dialog
        :title="titleMap[dialogStatus]"
        :visible.sync="dialogForRoleFetchingVisible"
      >
      <div class="Search">
        <el-form :inline="true" :model="query">
          <el-form-item>
            <el-select v-model="query.role.type" clearable placeholder="请选择类型">
              <el-option v-for="item in query.roleTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'ROLE_LIST'" type="primary" icon="el-icon-search" size="mini" @click="fetchRoleList">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'ROLE_EDIT'" type="success" icon="el-icon-plus" size="mini" @click="handleMgrRoleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="listLoading" :data="roleList" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="角色名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="角色代码" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="110" align="center" prop="type" :formatter="roleTypeFormater" />
        <el-table-column label="所属组织" width="110" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.organName }}</span>
          </template>
        </el-table-column>
      </el-table>
    
      <div class="block">
        <el-pagination :current-page="this.query.role.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="this.query.role.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="this.query.role.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
    </div>

    <div class="block">
      <!--弹框-->
      <el-dialog
        :title="titleMap[dialogStatus]"
        :visible.sync="dialogFormForAssignAuthorityVisible"
      >
        <el-form :inline="true" :model="organ" hidden>
          <el-form-item >
            <el-input v-model="organ.id" placeholder="待分配权限组织" />
          </el-form-item>
        </el-form>

        <el-tree
          ref="authorityTree"
          :data="authorityList"
          :default-expand-all="false"
          :props="defaultProps"
          :check-strictly="false"
          show-checkbox
          node-key="id"
          highlight-current
          @current-change="currentChange"
          @check-change="checkChange"
          @check="authorityTreeCheck"
        />

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormForAssignAuthorityVisible = false">取 消</el-button>
          <el-button type="primary" @click="getAssignAuthoritiesAndSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getList, doDelete, doEdit, querySubordinateOrgan } from '@/api/Organ'
import { getList as getOrganTypeList, getOriginOrganTypeAndOrganHasPagination } from '@/api/OrganType'
import { assignedOrganTypeOrgans } from '@/api/organTypeOrgan'
import { getBelong2OrganAndOthers } from '@/api/authority'
import { getOrganType } from '@/api/organType'
import { doEdit as doAddOrganAdminUser } from '@/api/User'
import { getAssignedPagination as getRoleList, doEdit as doAddMgrRoleEdit } from '@/api/role'
import { assignAndModifyOrganAuthority, getAssignedAuthorities , getOriginAssignedAuthorities, getOrganAuthoritiesAndAssigned } from '@/api/organAuthority'
import { getDictionaryGroup , getReferencedDictionaryList  } from '@/api/dictionary'
import { assignedDictionary } from '@/api/dictionaryOrgan'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct , getSelectedNodes , getSelectedNodesObject, getSystemErrorCode } from '@/api/utils'  
import localStorageUtil from '@/utils/localStorageUtil'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const typeMap = {
        '1': '超级管理员',
        '2': '管理员',
        '3': '普通用户'
      }
      const typeDesc = typeMap[status]
      return typeDesc
    }
  },
  data() {
    return {
      list: [],
      organTypeList:[],
      roleList:[],
      listLoading: true,
      dictionaryList:[],
      total: 5,
      currentPage: 1,
      pageSize: 10,
      organTypeListCurrentPage: 1,
      organTypeListPageSize: 10,
      organTypeListTotal: 0,
      dialogFormVisible: false,
      dialogFormForAddMgrUserVisible: false, // 添加超级管理员
      dialogFormForAssignAuthorityVisible: false, // 分配组织权限
      addForVisible: false,
      dialogForRoleAddVisible: false,
      dialogForRoleFetchingVisible: false,
      dialogForOrganTypeAvaliableEditVisible: false,
      dialogForDictionaryAddVisible: false,
      authorityList: [{}],
      organTypeSelection:[],
      defaultProps: {
        children: 'children',
        label: 'name',
        url: 'url'
      },
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      valueId: null, // 初始ID（可选）
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        checkStrictly: true,
        title: '组织'
        // disabled:true
      },
      title: '组织',
      defaultSelectedNodes: [],
      multipleDictionarySelection: [],
      form: {
        organName: '',
        organType:'',
        organPath: '',
        parentId: '',
        status: '',
        type: '',
        id: ''
      },
      role:{
        id : '',
        name: '管理员',
        code: 'ROLE_MGR',
        type: '1',
        organId:'',
        organPath:''
      },
      user:{
        id:'',
        userName:'',
        password:'',
        isSuperMgr:'',
        remark:''
      },
      organ: {
        id: '',
        organPath:'',
        tenantId:'',
        deletedAuthorities:[],
        assignedAuthorities:[]
      },
      optionData: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑',
        addMgrUser: '添加管理员账号',
        assignAuthority: '分配组织权限',
        addSub: '添加下级组织',
        assignRole: '添加管理员角色',
        addOrganType: '赋予可创建组织类型',
        referenceDictionary:'请选择要引用字典'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          name: '', // 角色名称
          status: '',
          type: '',
          organPath: ''
        },
        role: {
          name: '',
          code: '',
          type: '1',
          organId: '',
          organPath: '',
          tenantId:'',
          total: 5,
          currentPage: 1,
          pageSize: 10,
        },
        timeValue: '',
        roleTypeOptions: [],
        typeOptions: [],
        organTypeOptions: [],
        statusOptions: [{
          value: '0',
          label: '未启用'
        }, {
          value: '1',
          label: '启用'
        }],
        value: ''
      },
      organRules: {
        organName: [
          { required: true, message: '请输入组织名称', trigger: 'blur' }
        ]
      },
      userRules:{
        userName:[ { required: true, message: '请输入用户名称', trigger: 'blur' },
                   { min: 6, max: 128, message: '长度在 6 到 128 个字符', trigger: 'blur' }
                 ],
        password:[{ required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 6, max: 18, message: '长度在 8 到 18 个字符', trigger: 'blur' }],
        isSuperMgr:[{required: true, message: '请选择是否超', trigger: 'blur' }]
      },
    }
  },
  created() {
    this.initOrganTree(()=>{
      this.setOrganQueryType()
    })
    this.handleBuildTypeOptions()
    this.handleBuildStatusOptions()
    this.hadnleBuildSuperMgrOptions()
    this.handleBuildOrganTypeOptions()
    this.handleBuildRoleTypeOptions()
    this.fetchData()
  },
  methods: {
    statusFormat(row, column) {

      let label = ''
      for(let i = 0; i < this.query.statusOptions.length; i ++){
         if (''+row.status === this.query.statusOptions[i].value ){
             return  this.query.statusOptions[i].label
         }
      }
      return label

    },
    organTypeFormater(row, column){
      let label = ''
      for(let i = 0; i < this.query.typeOptions.length; i ++){
         if (''+row.organType === this.query.typeOptions[i].value ){
             return  this.query.typeOptions[i].label
         }
      }
      return label
    },
    typeFormat(row, column) {

      let label = ''
      for(let i = 0; i < this.query.typeOptions.length; i ++){
         if (''+row.type === this.query.typeOptions[i].value ){
             return  this.query.typeOptions[i].label
         }
      }
      return label
    },
    roleTypeFormater(row, column) {
      let label = ''
      for (let i = 0; i < this.query.roleTypeOptions.length; i++) {
        if ('' + row.type === this.query.roleTypeOptions[i].value) {
          return this.query.roleTypeOptions[i].label
        }

      }
      return label
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = handleBuildTreeDataStruct(data.entities, 'id', 'parentId')
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      //this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    initOrganTree(fn) {
      this.listLoading = true
      querySubordinateOrgan({ organId: getOrganId() }).then(response => {
          console.log(response)
          const data = response.data.data
          this.optionData = handleBuildTreeDataStruct(data, 'id', 'parentId')
          this.listLoading = false
          fn()
      })
    },
    setOrganQueryType(){
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes){
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
          this.query.params.organIds = []
          if (nodesInfo.length) {
              nodesInfo.forEach(function(element){
                  that.query.params.organIds.push(element.data.id)
              })
          }
      } else {             
          this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    organQueryModelChange(organQueryModel) {
      this.props.multiple=false
    
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()

    },
    organTypeListHandleSizeChange(val) {
      this.organTypeListCurrentPage = 1
      this.organTypeListPageSize = val
      this.fetchOrganTypeList()
    },
    organTypeListHandleCurrentChange(val) {
      this.organTypeListCurrentPage = val
      this.fetchOrganTypeList()

    },
    handleOrganTypeSelectionChange(selectionList){

      this.organTypeSelection = selectionList

    },
    handleOrganTypeOrganSave(){

      let organTypeSelected = []
      for( let i = 0; i < this.organTypeSelection.length ; i ++ ){
          let organTypeOrgan = {}
          organTypeOrgan['belongToOrganId'] = this.organ.id
          organTypeOrgan['organTypeId'] = this.organTypeSelection[i].id
          organTypeOrgan['organId'] = getOrganId()
          organTypeOrgan['organPath'] = getOrganPath()
          organTypeOrgan['organTypeName'] = this.organTypeSelection[i].organTypeName
          organTypeSelected.push(organTypeOrgan)
      }


      this.$confirm('此操作将会影响记录的组织类型创建, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              center: true
            }).then(() => {

              this.listLoading = true
              assignedOrganTypeOrgans( organTypeSelected, this.organ.id ).then(response => {
                 const data = response.data
                 if (data.status > 0) {
                  this.$message({
                    type: 'success',
                    message: '操作成功!'
                  })
                } else if (data.status === 403) {
                  this.$message({
                    type: 'warning',
                    message: data.description
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: '操作失败!'
                  })
                }
                this.listLoading = false
              })
      })
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.createBy = ''
      this.form.createDate = ''
      this.form.id = ''
      this.form.organName = ''
      this.form.organPath = ''
      this.form.parentId = getOrganId()
      this.form.remark = ''
      this.form.status = '1'
      this.form.type = '1'
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      debugger
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.id = row.id
      this.form.organName = row.organName
      this.form.organPath = row.organPath
      this.form.organType = ''+row.organType
      this.form.parentId = row.parentId
      this.form.remark = row.remark
      this.form.status = '' + row.status
      this.form.type = ''+row.type
      this.form.updateBy = row.updateBy
      this.form.updateDate = row.updateDate
      this.form.tenantId = row.parentId
      this.addForVisible = true

      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleAddSub(index, row) {
      this.form.createBy = ''
      this.form.createDate = ''
      this.form.id = ''
      this.form.organName = ''
      this.form.organPath = ''
      this.form.parentId = row.id
      this.form.remark = ''
      this.form.status = '1'
      this.form.type = '1'
      this.form.updateBy = ''
      this.form.updateDate = ''

      this.addForVisible = false
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'addSub'
    },
    handleFetchRoleList(index , row){

      this.query.role.organId = row.id
      this.query.role.organPath = row.organPath
      this.query.role.tenantId = row.tenantId
  
      this.dialogForRoleFetchingVisible = true
      this.organ = row
      this.fetchRoleList()
    },
    fetchRoleList(){
      
      getRoleList(this.query.role, this.query.role.currentPage, this.query.role.pageSize ).then(response => {
        const data = response.data
        this.query.role.total = data.totalCount
        this.query.role.pageSize = data.pageSize
        this.query.role.currentPage = data.currentPage
        this.roleList = data.entities
        this.listLoading = false
      })
    },
    // 新增
    handleMgrRoleAdd() {

      // 显示弹框
      this.dialogForRoleAddVisible = true
      // 新增弹框标题
      this.dialogStatus = 'assignRole'
      this.role.id = ''
      this.role.name = ''
      this.role.code = ''
      this.addForVisible = false
    },

    handleMgrRoleSave(){

      this.role.organId = this.organ.id
      this.role.organPath = this.organ.organPath
      this.role.tenantId = this.organ.tenantId
      this.role.createBy = getCurrentLoginUserId()
      this.role.updateBy = getCurrentLoginUserId()
      doAddMgrRoleEdit(this.role).then(response => {
        console.log(response)
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          //this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogForRoleAddVisible = false
      })
    },
    handleAddOrganTypeAvaliableEdit(index, row){
     
      // 编辑弹框标题
      this.dialogStatus = 'addOrganType'
      this.dialogForOrganTypeAvaliableEditVisible = true
      this.organ.id = row.id
      this.fetchOrganTypeList(row)

    },
    fetchOrganTypeList(row ){

      let params = {}
      params['organPath'] = getOrganPath()
      params['organId'] = row.id
      params['originId'] = getOrganId()
      this.listLoading = true
      getOriginOrganTypeAndOrganHasPagination(params,
        this.organTypeListCurrentPage, 
        this.organTypeListPageSize).then(response => {
        const data = response.data

        this.organTypeListTotal = data.totalCount
        this.organTypeListPageSize = data.pageSize
        this.organTypeListCurrentPage = data.currentPage
        this.organTypeList = data.entities

        let selectionOrganTypeList = getSelectedNodesObject(this.organTypeList, 'hasOrganType')
        this.listLoading = false
        this.$nextTick(function(){
          selectionOrganTypeList.forEach(row => {
            this.$refs.organTypeSelectionTable.toggleRowSelection(row);
          })
        })


      })

    },
    handleDelete(index, row) {

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    handleUserEditSave(formName) {


        this.$refs[formName].validate((valid) => {
          if (valid) {

            this.user.organId = this.organ.id
            this.user.organPath = this.organ.organPath
            this.user.createBy = getCurrentLoginUserId()
            this.user.updateBy = getCurrentLoginUserId()
            doAddOrganAdminUser(this.user).then(response => {
                console.log(response)
                const data = response.data
                if (data.status) {
                  this.$message({
                    type: 'success',
                    message: '操作成功!'
                  })
                  this.fetchData()
                } else {
                  this.$message({
                    type: 'info',
                    message: '操作失败!'
                  })
                }
                this.listLoading = false
                this.dialogFormForAddMgrUserVisible = false
              })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleEditSave(formName) {
      this.$refs[formName].validate((valid) => {
        debugger
        if (valid) {
          this.form.createBy = getCurrentLoginUserId()
          this.form.updateBy = getCurrentLoginUserId()

          doEdit(this.form).then(response => {
            debugger
            console.log(response)
            const data = response.data
            if (data.status) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData()
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
            this.listLoading = false
            this.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAddMgrUser(index, row) {
      // 编辑弹框标题
      this.dialogStatus = 'addMgrUser'
      this.dialogFormForAddMgrUserVisible = true
      this.organ.id = row.id
      this.organ.organPath = row.organPath

    },
    handleRoleAssgin(index, row) {
      // 编辑弹框标题
      this.dialogStatus = 'assignRole'
      this.dialogForRoleAddVisible = true

    },
    
    fetchAuthorityList(index, row) {
      this.authlistLoading = true

      getOrganAuthoritiesAndAssigned({"organId": row.id, "tenantId":row.tenantId}).then(response => {
        const gateway = response.data
        debugger
        const selectedNodes = getSelectedNodes(gateway.data,'hasAuthority')
        this.authorityList = handleBuildTreeDataStruct(gateway.data,'id', 'parentId')
        this.authlistLoading = false

        // this.setCheckedNodes(selectedNodes);
        this.defaultSelectedNodes = selectedNodes
        this.$nextTick(function(){
          this.handleDefaultSelected(selectedNodes)
        })
      })
    },
    fetchDictionaryList(index, row){

      getReferencedDictionaryList({sys:1, originId: getOrganId(), organId: row.id}).then(response => {
        debugger
        const gateway = response.data
        const selectedNodes = getSelectedNodesObject(gateway.data,'hasReferenced')
        this.dictionaryList = handleBuildTreeDataStruct(gateway.data, 'id', 'parentId')
        this.authlistLoading = false

        this.$nextTick(function(){
          selectedNodes.forEach(row => {
            this.$refs.dictionaryListTable.toggleRowSelection(row);
          })
        })
      })
    },
    handleDefaultSelected(selectedNodes){
      for(let i = 0; i < selectedNodes.length; i++ ){
          this.$refs.authorityTree.setChecked( selectedNodes[i], true, false)
        }
    },
    handleAssignAuthority(index, row) {
      // 编辑弹框标题
      this.dialogStatus = 'assignAuthority'
      this.dialogFormForAssignAuthorityVisible = true
      this.organ.id = row.id
      this.organ.tenantId = row.tenantId
      this.fetchAuthorityList(index, row)
    },
    authorityTreeCheck(data, statusObj){
      console.log(data)
      console.log(statusObj)

      /*const checkedList = statusObj.checkedNodes
      let checkedNodesAppend = [];

      for(let i = 0; i < checkedList.length; i++ ){

        if(!checkedList[i].hasAuthority){//当前选中，但未持久化到系统中
            checkedNodesAppend.push(checkedList[i])
        }

      }
      for(let i = 0; i < checkedNodesAppend.length; i++ ){
          this.organ.assignedAuthorities.push(checkedNodesAppend[i])
      }
        
      if(data.hasAuthority){
          this.organ.deletedAuthorities.push(data)
      }else{
          this.organ.assignedAuthorities.push(data)
      } 

      //TODO 当前点击节点取消选中的情况
      if(data.children){
          this.organ.deletedAuthorities.push(data)
          for(let i = 0; i < data.children.length ; i ++){
              this.organ.deletedAuthorities.push(data.children[i])
          }
      }*/

      //操作点击后

    },
    handleSaveAuthority(){

    },
    getAssignAuthoritiesAndSave(){
      //TODO 获取组织当前指派的权限, 包括组织类型所属权限

      this.$confirm('此操作将会更改所选组织的权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {

        const checkedList = this.$refs.authorityTree.getCheckedNodes()
        const halfCheckList = this.$refs.authorityTree.getHalfCheckedNodes()
        const batchModify = []
        const allChecked = []

        for (let i = 0; i < checkedList.length; i++) {
          allChecked.push(checkedList[i])
        }

        for (let i = 0; i < halfCheckList.length; i++) {
          allChecked.push(halfCheckList[i])
        }

        for (let i = 0; i < allChecked.length; i++) {
          const organAuthority = {}
          organAuthority['id'] = allChecked[i].organAuthorityId
          organAuthority['authId'] = allChecked[i].id
          organAuthority['organId'] = this.organ.id
          organAuthority['parentAuthId'] = allChecked[i].parentId
          organAuthority['authName'] = allChecked[i].name
          organAuthority['isDeleted'] = false
          batchModify.push(organAuthority)
        
        }
        //指定、修改组织权限
        assignAndModifyOrganAuthority(batchModify, this.organ.tenantId, this.organ.id ).then(response => {
          console.log(response)
          const data = response.data
          if(data.successful){
            this.$message({
              type: 'success',
              message: getSystemErrorCode(data.status)
            })
          } else {
             this.$message({
              type: 'info',
              message: getSystemErrorCode(data.status)
            })
          }
         
        })

 
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })

    },
    getCheckedAuthorityNodes(){

    },
    handleAddDictionaryAvaliableEdit(index, row){
      this.dialogStatus = 'referenceDictionary'
      this.dialogForDictionaryAddVisible = true
      this.organ.id = row.id
      this.fetchDictionaryList(index, row)
    },
    handleDictionaryEditSave(){
    
      this.$confirm('此操作将会更改所选组织的引用字典, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {

        debugger
        let directionOrganList = []
        for(let i = 0; i < this.multipleDictionarySelection.length ; i++ ){

          let dictionaryOrgan = {}

              dictionaryOrgan['belongToOrganId'] = this.organ.id
              dictionaryOrgan['dictionaryDesc'] = this.multipleDictionarySelection[i].desc
              dictionaryOrgan['dictionaryId'] = this.multipleDictionarySelection[i].id
              dictionaryOrgan['organId'] = getOrganId()
              dictionaryOrgan['organPath'] = getOrganPath()
              dictionaryOrgan['belongToOrganId'] = this.organ.id
              directionOrganList.push(dictionaryOrgan)
        }
        assignedDictionary(directionOrganList, this.organ.id).then(response => {
           const data = response.data
          if (data.status < 20000 && data.status >= 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.dialogFormForAssignAuthorityVisible = false
          } else if (data.status === 50403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
           
        }) .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })

    },
    hadnleBuildSuperMgrOptions(){
      debugger
      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserSuperManager" && item.parentId != '0';
      })
      let isSuperMgrOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        isSuperMgrOptions.push(option)
      }
      this.query.isSuperMgrOptions = isSuperMgrOptions

      // getDictionaryGroup({sys:1, bigType:"UserSuperManager",organId: getOrganId()}).then(response => {
      //     const data = response.data
      //     let isSuperMgrOptions = [];
      //     for( let i =0; i < data.length; i ++ ){

      //       let option = {}
      //       option['value'] = data[i].value
      //       option['label'] = data[i].desc
      //       isSuperMgrOptions.push(option)
      //     }
      //     this.query.isSuperMgrOptions = isSuperMgrOptions
      // })
    },
    handleBuildOrganTypeOptions(){

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "OrganType" && item.parentId != '0';
      })
      let organTypeOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        organTypeOptions.push(option)
      }
      this.query.organTypeOptions = organTypeOptions
    },
    handleBuildTypeOptions(){

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "OrganType" && item.parentId != '0';
      })
      let typeOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        typeOptions.push(option)
      }
      this.query.typeOptions = typeOptions
    },
    handleBuildRoleTypeOptions(){
      debugger
      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserRole" && item.parentId != '0';
      })
      let roleTypeOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        roleTypeOptions.push(option)
      }
      this.query.roleTypeOptions = roleTypeOptions
    },
    handleBuildStatusOptions(){


      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "OrganStatus" && item.parentId != '0';
      })
      let statusOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        statusOptions.push(option)
      }
      this.query.statusOptions = statusOptions
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange(selection){
      this.multipleDictionarySelection = selection

    },
    checkChange(nodeData, nodeChecked, childChecked) {

    },
    setCheckedNodes(nodes) {
      this.$refs.tree.setCheckedNodes(nodes)
    },
    getCheckedNodes() {

    },
    currentChange(currentNodeData, currentNode) {
      console.log(currentNodeData)
      console.log(currentNode)
    },
    getValue(value) {
      this.valueId = value
      this.query.params.organPath = value.organPath
      console.log(this.valueId)
    },
    flushPage(e){
      setTimeout(() => {
        this.$set(this.form, 'organType', e.target.value)
      }, 100)

    }

  }
}
</script>
